﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using VirtualPress.Portal.WebLogic.Authentication;
using VirtualPress.Portal.WebLogic;
using VirtualPress.Infrastructure.Entities.Enum;
using System.Web.Mvc;
using VirtualPress.Infrastructure.Entities.Entity;
using VirtualPress.Portal.Web.Areas.WorkSpace.Models;
using VirtualPress.Portal.Biz;
using VirtualPress.Tool.Framework;
using System.IO;
using System.Linq.Expressions;
using VirtualPress.Infrastructure.Entities.Repository;

namespace VirtualPress.Portal.Web.Areas.WorkSpace.Controllers
{
#if !DEBUG
    [ErrorHandle]
#endif
    [Auth(UserRole.Member)]
    [WorkSpace(UserRole.Member)]
    public class MemberController : Controller
    {
        public ActionResult Index()
        {
            List<int> pass = new List<int>(){
                (int)ArticleStatus.ChuBanYiJiaoFei,
                (int)ArticleStatus.DaiChuBan,
                (int)ArticleStatus.LuYong,
            };
            List<int> examine = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            string username = HttpContext.User.Identity.Name;

            MemberIndexCount box = iCache.Get<MemberIndexCount>(
                String.Format("Member/Index/{0}/Count", username),
                () =>
                {
                    return new MemberIndexCount()
                    {
                        ArticleCount = new Article().Count(c => c.UserName == username && !c.IsDelete),
                        PublishArticle = new Article().Count(c => c.UserName == username && !c.IsDelete && c.Status == (int)ArticleStatus.YiChuBan),
                        PassArticleCount = new Article().Count(c => c.UserName == username && !c.IsDelete && pass.Contains(c.Status)),
                        ExamineArticleCount = new Article().Count(c => c.UserName == username && !c.IsDelete && examine.Contains(c.Status)),
                        MyJournal = JournalBiz.GetFavourForPage(HttpContext.User.Identity.Name)
                    };
                }, 600);
            ViewBag.ArticleCount = box.ArticleCount;
            ViewBag.PassArticleCount = box.PassArticleCount;
            ViewBag.PublishArticle = box.PublishArticle;
            ViewBag.ExamineArticleCount = box.ExamineArticleCount;
            ViewBag.MyJournalCount = box.MyJournal;
            ViewBag.ExamineArticle = iCache.Get<List<Article>>(
                String.Format("Artice.FindAllForExamineTo{0},{1},{2}", username, 0, 5),
                () => { return new Article().FindAll(c => c.UserName == username && !c.IsDelete && examine.Contains(c.Status), c => c.Id, 0, 5); },
                600);
            ViewBag.MyJournal = iCache.Get<List<Favour>>(
                String.Format("JournalBiz.GetFavour({0}, 0, 5)", username),
                () => { return JournalBiz.GetFavour(username, 0, 5); },
                600);
            return View();
        }
        #region 投稿
        #region 期刊投稿
        public ActionResult ChooseJournal(int page = 0, int indtype = 0, int journalId = -1)
        {
            if (journalId > -1)
            {
                return RedirectToAction("Contribute", new { journal = journalId });
            }
            var author = new Author().Find(c => c.UserName == HttpContext.User.Identity.Name);
            if (author == null)
            {
                return RedirectToAction("AuthorInfo", new { rdc = "ChooseJournal" });
            }
            var journals = new ItemListBox<Periodical>(JournalBiz.GetAllJournal(c => c.IndType == indtype && c.IsActive, page, 15))
                .BuildPage(JournalBiz.GetAllJournalForPage(c => c.IndType == 0 && c.IsActive), page, 15,
                new PageParameter() { Style = "workspace" });
            ViewBag.Journals = journals;
            ViewBag.IndType = indtype;
            ViewBag.Page = page;
            return View();
        }
        [HttpPost]
        public ActionResult ChooseJournal(int IndType, int Journal)
        {
            var journal = new Periodical().Find(Journal.ToString());
            if (journal != null && journal.IndType == (Profession)IndType)
            {
                return RedirectToAction("Contribute", new { journal = journal.Id });
            }
            return RedirectToAction("ChooseJournal");
        }
        /// <summary>
        /// 投稿
        /// </summary>
        /// <param name="journal"></param>
        /// <returns></returns>
        public ActionResult Contribute(int journal)
        {
            var entity = new Periodical().Find(journal.ToString());
            ViewBag.Journal = entity;
            var author = new Author().FindAll(c => c.UserName == HttpContext.User.Identity.Name);
            ViewBag.Author = author;
            return View();
        }
        /// <summary>
        /// 投稿
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Contribute(ContributeModel model)
        {
            if (!JournalBiz.Contribute(new Article()
            {
                ArticleType = Infrastructure.Entities.Enum.ArticleType.Journal,
                Abstract = model.Abstract.Replace("\r\n", "<br/>"),
                Abstract_EN = model.Abstract_EN.Replace("\r\n", "<br/>"),
                CreateTime = DateTime.Now,
                KeyWords = model.KeyWords,
                KeyWords_EN = model.KeyWords_EN,
                Peri_Id = model.journalId,
                Status = ArticleStatus.Open,
                Title = model.Title,
                Title_EN = model.Title_EN,
                UserName = HttpContext.User.Identity.Name,
                SubmitTime = DateTime.Now,
                IsDelete = false,
                GJFW = String.IsNullOrEmpty(model.GJFW) ? "" : (model.GJFW.EndsWith(";") ? model.GJFW.Remove(model.GJFW.Length - 1) : model.GJFW)
            }, model.Author.Split(';').ToList()))
            {
                RedirectToAction("Contribute", new { journal = model.journalId });
            }
            return RedirectToAction("Article");
        }
        #endregion

        #region 会议投稿
        public ActionResult ChooseMeeting(int page = 0, int indtype = 0, int meetingId = -1)
        {
            if (meetingId > -1)
            {
                return RedirectToAction("Contribute", new { meeting = meetingId });
            }
            var author = new Author().Find(c => c.UserName == HttpContext.User.Identity.Name);
            if (author == null)
            {
                return RedirectToAction("AuthorInfo", new { rdc = "ChooseMeeting" });
            }
            var meetings = new ItemListBox<Meeting>(MeetingBiz.GetAllMeeting(c => c.IndType == indtype && c.isActive, page, 15))
                .BuildPage(MeetingBiz.GetAllMeetingForPage(c => c.IndType == 0 && c.isActive), page, 15,
                new PageParameter() { Style = "workspace" });
            ViewBag.Meetings = meetings;
            ViewBag.IndType = indtype;
            ViewBag.Page = page;
            return View();
        }
        [HttpPost]
        public ActionResult ChooseMeeting(int IndType, int Meeting)
        {
            var meeing = new Meeting().Find(Meeting.ToString());
            if (meeing != null && meeing.IndType == (Profession)IndType)
            {
                return RedirectToAction("ArticleSubmit", new { Meeting = meeing.Id });
            }
            return RedirectToAction("ChooseMeeting");
        }
        public ActionResult ArticleSubmit(int meeting)
        {
            var entity = new Meeting().Find(meeting.ToString());
            if (entity == null)
            {
                return Redirect("/");
            }
            ViewBag.Meeting = entity;
            var author = new Author().FindAll(c => c.UserName == HttpContext.User.Identity.Name);
            ViewBag.Author = author;
            return View();
        }
        #endregion
        [HttpPost]
        public ActionResult ArticleSubmit(MeetingContributeModel model)
        {

            if (!MeetingBiz.Contribute(new Article()
            {
                ArticleType= Infrastructure.Entities.Enum.ArticleType.Meeting,
                Abstract = model.Abstract.Replace("\r\n", "<br/>"),
                Abstract_EN = model.Abstract_EN.Replace("\r\n", "<br/>"),
                CreateTime = DateTime.Now,
                KeyWords = model.KeyWords,
                KeyWords_EN = model.KeyWords_EN,
                Conference_Id=model.meetingId,
                Status = ArticleStatus.Open,
                Title = model.Title,
                Title_EN = model.Title_EN,
                UserName = HttpContext.User.Identity.Name,
                SubmitTime = DateTime.Now,
                IsDelete = false,
                GJFW = String.IsNullOrEmpty(model.GJFW) ? "" : (model.GJFW.EndsWith(";") ? model.GJFW.Remove(model.GJFW.Length - 1) : model.GJFW)
            }, model.Author.Split(';').ToList()))
            {
                RedirectToAction("ArticleSubmit", new { meeting = model.meetingId });
            }
            return RedirectToAction("Manuscript");
        }
        #endregion

        #region 稿件中心

        #region 期刊稿件
        public ActionResult ArticleDetail(int id)
        {
            var article = new Article().Find(c => c.Id == id && c.ArticleType == (int)ArticleType.Journal && c.UserName == HttpContext.User.Identity.Name);
            if (article.Status == ArticleStatus.Open) //当待审核时，允许编辑
            {
                return RedirectToAction("ArticleEdit", new { id = id });
            }
            var author = new ArticleAuthor().FindAll(c => c.ManuscriptId == article.Id);
            //作者信息
            ViewBag.ArticleAuthor = author;
            //稿件
            ViewBag.Article = article;
            //期刊
            ViewBag.Journal = new Periodical().Find(article.Peri_Id.ToString());
            //附件
            ViewBag.Attachment = new Appendix().FindAll(c=> c.Type == (int)AttachmentType.Manuscript && c.RaletionId == article.Id);
            //稿件历史
            ViewBag.History = JournalBiz.GetAllArticleHistory(article.Id);
            //专家推荐材料
            ViewBag.Recommendation = new Appendix().Find(c => c.Type == (int)AttachmentType.Recommendation && c.RaletionId == article.Id);
            //审稿记录
            ViewBag.AuditingRecord = JournalBiz.GetAllAuditingRecord(article.Id);
            return View();
        }
        public ActionResult ArticleEdit(int id)
        {
            var article = new Article().Find(c => c.Id == id && c.UserName == HttpContext.User.Identity.Name);
            if (article.Status != ArticleStatus.Open)
            {
                return RedirectToAction("Article");
            }
            //作者信息
            var author = new Author().FindAll(c => c.UserName == HttpContext.User.Identity.Name);
            ViewBag.Author = author;

            var articleAuthor = new ArticleAuthor().FindAll(c => c.ManuscriptId == article.Id);
            //稿件作者信息
            ViewBag.ArticleAuthor = articleAuthor;//作者信息
            //稿件
            ViewBag.Article = article;
            //期刊
            ViewBag.Journal = new Periodical().Find(article.Peri_Id.ToString());
            //附件
            ViewBag.Attachment = new Appendix().Find(c=>c.Type == (int)AttachmentType.Manuscript && c.RaletionId == article.Id);
            //专家推荐材料
            ViewBag.Recommendation = new Appendix().Find(c => c.Type == (int)AttachmentType.Recommendation && c.RaletionId == article.Id);
            //稿件历史
            ViewBag.History = JournalBiz.GetAllArticleHistory(article.Id);
            //审稿记录
            ViewBag.AuditingRecord = JournalBiz.GetAllAuditingRecord(article.Id);
            return View();
        }
        [HttpPost]
        public ActionResult ArticleEdit(ContributeModel model)
        {
            var article = new Article().Find(Request.Form["ArticleId"]);
            article.Abstract = model.Abstract.Replace("\r\n","<br/>");
            article.Abstract_EN = model.Abstract_EN.Replace("\r\n", "<br/>");
            article.KeyWords = model.KeyWords;
            article.KeyWords_EN = model.KeyWords_EN;
            article.Title = model.Title;
            article.Title_EN = model.Title_EN;
            article.GJFW = model.GJFW.EndsWith(";") ? model.GJFW.Remove(model.GJFW.Length - 1) : model.GJFW;
            JournalBiz.ArticleEdit(article, model.Author.Split(';').ToList());
            return RedirectToAction("Article", new { type = Request.Form["Status"] });
        }
        [HttpPost]
        public ActionResult ArticleRevise(int ArticleId)
        {
            JournalBiz.ArticleEdit(ArticleId);
            return RedirectToAction("ArticleDetail", new { id = ArticleId });
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="type">
        /// 0: 待审核 0
        /// 1: 专审待缴费1 专审待分配2 专审中3 专审完成4 专审修订5 专审修订完成6
        /// 2: 终审中7 终审完成8 终审修订9  终审修订完成10 
        /// 10: 出版待缴费30 出版已缴费31 录用20
        /// 20: 出版40 
        /// 99: 拒绝稿件99
        /// -1: 所有稿件
        /// </param>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult Article(int type = 0, int page = 0)
        {
            var groupmap = new
            {
                最新 = new List<int>() { 0 },
                专审 = new List<int>() { 1, 2, 3, 4, 5, 6 },
                终审 = new List<int>() { 7, 8, 9, 10 },
                录用 = new List<int>() { 20, 30, 31 },
                出版 = new List<int>() { 40 },
                拒绝 = new List<int>() { 99 }
            };

            Expression<Func<T_Article, bool>> where = null;
            if (type == -1)
            {
                where = c => c.UserName == HttpContext.User.Identity.Name;
            }
            else
            {
                List<int> contain = new List<int>();
                switch (type)
                {
                    default:
                    case 0:
                        contain = groupmap.最新;
                        break;
                    case 1:
                        contain = groupmap.专审;
                        break;
                    case 2:
                        contain = groupmap.终审;
                        break;
                    case 20:
                        contain = groupmap.录用;
                        break;
                    case 40:
                        contain = groupmap.出版;
                        break;
                    case 99:
                        contain = groupmap.拒绝;
                        break;
                }
                where = c => c.UserName == HttpContext.User.Identity.Name && !c.IsDelete && contain.Contains(c.Status);
            }
            List<Article> list = JournalBiz.GetAllArticle(where, page, 20);
            var data = new ItemListBox<Article>(list).BuildPage(
                JournalBiz.GetAllArticleForPage(where),
                page,20,
                new PageParameter(){
                    IsActive=false,
                    Param_page="page",
                    Style="workspace"
                });
            ViewBag.Article = data;
            ViewBag.Type = type;
            return View();
        }
        public ActionResult CancelArticle(int id, int type = 0)
        {
            JournalBiz.CancelArticle(id);
            return RedirectToAction("Article", new { type = type });
        }
        public ActionResult ShowSuggestion(int id)
        {
            Appendix attachment = new Appendix().Find(id.ToString());
            if (attachment.Own != HttpContext.User.Identity.Name)
            {
                return Redirect("/workspace/member/index");
            }
            ViewBag.Attachment = attachment;
            return View();
        }
        #endregion

        #region 会议稿件
        public ActionResult Manuscript(int type = 0, int page = 0)
        {
            var groupmap = new
            {
                最新 = new List<int>() { 0 },
                专审 = new List<int>() { 1, 2, 3, 4, 5, 6 },
                终审 = new List<int>() { 7, 8, 9, 10 },
                录用 = new List<int>() { 20, 30, 31 },
                出版 = new List<int>() { 40 },
                拒绝 = new List<int>() { 99 }
            };

            Expression<Func<T_Article, bool>> where = null;
            if (type == -1)
            {
                where = c => c.UserName == HttpContext.User.Identity.Name;
            }
            else
            {
                List<int> contain = new List<int>();
                switch (type)
                {
                    default:
                    case 0:
                        contain = groupmap.最新;
                        break;
                    case 1:
                        contain = groupmap.专审;
                        break;
                    case 2:
                        contain = groupmap.终审;
                        break;
                    case 20:
                        contain = groupmap.录用;
                        break;
                    case 40:
                        contain = groupmap.出版;
                        break;
                    case 99:
                        contain = groupmap.拒绝;
                        break;
                }
                where = c => c.UserName == HttpContext.User.Identity.Name && !c.IsDelete && contain.Contains(c.Status);
            }
            List<Article> list = MeetingBiz.GetAllArticle(where,false, page, 20);
            var data = new ItemListBox<Article>(list).BuildPage(
                MeetingBiz.GetAllArticleForPage(where),
                page, 20,
                new PageParameter()
                {
                    IsActive = false,
                    Param_page = "page",
                    Style = "workspace"
                });
            ViewBag.Article = data;
            ViewBag.Type = type;
            return View();
        }
        public ActionResult cancelManuscript(int id, int type = 0)
        {
            MeetingBiz.CancelArticle(id);
            return RedirectToAction("Manuscript", new { type = type });
        }
        public ActionResult ManuscriptDetail(int id)
        {
            var article = new Article().Find(c => c.Id == id && c.ArticleType == (int)ArticleType.Meeting && c.UserName == HttpContext.User.Identity.Name);
            if (article.Status == ArticleStatus.Open) //当待审核时，允许编辑
            {
                return RedirectToAction("ManuscriptEdit", new { id = id });
            }
            var author = new ArticleAuthor().FindAll(c => c.ManuscriptId == article.Id);
            //作者信息
            ViewBag.ArticleAuthor = author;
            //稿件
            ViewBag.Article = article;
            //期刊
            ViewBag.Meeting = new Meeting().Find(article.Conference_Id.ToString());
            //附件
            ViewBag.Attachment = new Appendix().FindAll(c => c.Type == (int)AttachmentType.Manuscript && c.RaletionId == article.Id);
            //稿件历史
            ViewBag.History = MeetingBiz.GetAllArticleHistory(article.Id);
            //专家推荐材料
            ViewBag.Recommendation = new Appendix().Find(c => c.Type == (int)AttachmentType.Recommendation && c.RaletionId == article.Id);
            //审稿记录
            ViewBag.AuditingRecord = MeetingBiz.GetAllAuditingRecord(article.Id);
            return View();
 
        }
        public ActionResult ManuscriptEdit(int id)
        {
            var article = new Article().Find(c => c.Id == id && c.ArticleType == (int)ArticleType.Meeting && c.UserName == HttpContext.User.Identity.Name);
            if (article.Status != ArticleStatus.Open)
            {
                return RedirectToAction("Manuscript");
            }
            //作者信息
            var author = new Author().FindAll(c => c.UserName == HttpContext.User.Identity.Name);
            ViewBag.Author = author;

            var articleAuthor = new ArticleAuthor().FindAll(c => c.ManuscriptId == article.Id);
            //稿件作者信息
            ViewBag.ArticleAuthor = articleAuthor;//作者信息
            //稿件
            ViewBag.Article = article;
            //期刊
            ViewBag.Meeting = new Meeting().Find(article.Conference_Id.ToString());
            //附件
            ViewBag.Attachment = new Appendix().Find(c => c.Type == (int)AttachmentType.Manuscript && c.RaletionId == article.Id);
            //专家推荐材料
            ViewBag.Recommendation = new Appendix().Find(c => c.Type == (int)AttachmentType.Recommendation && c.RaletionId == article.Id);
            //稿件历史
            ViewBag.History = MeetingBiz.GetAllArticleHistory(article.Id);
            //审稿记录
            ViewBag.AuditingRecord = MeetingBiz.GetAllAuditingRecord(article.Id);
            return View();
        }
        [HttpPost]
        public ActionResult ManuscriptEdit(MeetingContributeModel model)
        {
            var article = new Article().Find(Request.Form["ArticleId"]);
            article.Abstract = model.Abstract.Replace("\r\n", "<br/>");
            article.Abstract_EN = model.Abstract_EN.Replace("\r\n", "<br/>");
            article.KeyWords = model.KeyWords;
            article.KeyWords_EN = model.KeyWords_EN;
            article.Title = model.Title;
            article.Title_EN = model.Title_EN;
            article.GJFW = model.GJFW.EndsWith(";") ? model.GJFW.Remove(model.GJFW.Length - 1) : model.GJFW;
            MeetingBiz.ArticleEdit(article, model.Author.Split(';').ToList());
            return RedirectToAction("Manuscript", new { type = Request.Form["Status"] });
        }
        public ActionResult ManuscriptRevise(int ArticleId)
        {
            MeetingBiz.ArticleEdit(ArticleId);
            return RedirectToAction("ManuscriptDetail", new { id = ArticleId });
        }
        #endregion

        #endregion

        #region 个人中心、作者信息
        public ActionResult Author(int page = 0)
        {
            var list = new ItemListBox<Author>(UserBiz.GetAllAuthor(HttpContext.User.Identity.Name, page, 20));
            list.BuildPage(UserBiz.GetAllAuthorForPage(HttpContext.User.Identity.Name),
                page,
                20,
                 new PageParameter()
                 {
                     IsActive = false,
                     Param_page = "page",
                     Style = "workspace"
                 });
            ViewBag.Author = list;
            return View();
        }
        public ActionResult AuthorInfo(string rdc="")
        {
            if (!String.IsNullOrEmpty(rdc))
            {
                ViewBag.Rdc = rdc;
            }
            return View();
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult NewAuthor(NewAuthorModel model,string rdc="")
        {
            UserBiz.SaveNewAuthor(new Author() { 
                Address=model.Address,
                CreateTime=DateTime.Now,
                Degree=model.Degree,
                Department=model.Department,
                Department_EN=model.Department_EN,
                Email=model.Email,
                FirstName=model.FirstName,
                Gender= (Gender)model.Gender,
                Introduction=model.Introduction,
                Introduction_EN=model.Introduction_EN,
                LastName=model.LastName,
                PostCode=model.PostCode,
                Title=model.Title,
                Title_EN=model.Title_EN,
                UserName=HttpContext.User.Identity.Name,
                Phone = model.Phone
            });
            if (!String.IsNullOrEmpty(rdc))
            {
                return RedirectToAction(rdc);
            }
            return RedirectToAction("Author");
        }
        public ActionResult CancelAuthor(int id)
        {
            var author = new Author().Find(c => c.Id == id && c.UserName == HttpContext.User.Identity.Name);
            if (author != null)
            {
                author.PostDelete();
            }
            return RedirectToAction("Author");
        }
        /// <summary>
        /// 我的期刊 收藏与投过稿的期刊
        /// </summary>
        /// <returns></returns>
        public ActionResult MyJournals(int page=0)
        {
            ItemListBox<Favour> data = new ItemListBox<Favour>();
            data.Data = JournalBiz.GetFavour(HttpContext.User.Identity.Name, page, 10);
            data.BuildPage(JournalBiz.GetFavourForPage(HttpContext.User.Identity.Name), page, 10,
                new PageParameter()
                {
                    Param_page = "page",
                    Style = "workspace"
                });
            ViewBag.Data = data;
            return View();
        }
        /// <summary>
        /// 待办事项
        /// </summary>
        /// <returns></returns>
        public ActionResult TodoList()
        {
            return View();
        }
       
        #endregion 
        
        #region 缴费管理
        public ActionResult Bill(int page = 0) 
        {
            int itemCount = PaymentBiz.GetAllBillForPage(c => c.Own == HttpContext.User.Identity.Name && c.Status == (int)BillStatus.DaiZhiFu);
            ItemListBox<Reckoning> data = new ItemListBox<Reckoning>(
                PaymentBiz.GetAllBill(c => c.Own == HttpContext.User.Identity.Name && c.Status == (int)BillStatus.DaiZhiFu, page, 10))
                .BuildPage(
                    itemCount,
                    page, 10, new PageParameter()
                    {
                        IsActive = false,
                        Param_page = "page",
                        Style = "workspace"
                    });
            ViewBag.Data = data;
            return View();
        }
        public ActionResult BillLog(int page = 0)
        {
            int itemCount = PaymentBiz.GetAllBillForPage(c => c.Own == HttpContext.User.Identity.Name && c.Status==2);
            ItemListBox<Reckoning> data = new ItemListBox<Reckoning>(
                PaymentBiz.GetAllBill(c => c.Own == HttpContext.User.Identity.Name && c.Status == 2, page, 10))
                .BuildPage(
                    itemCount,
                    page, 10, new PageParameter()
                    {
                        IsActive = false,
                        Param_page = "page",
                        Style = "workspace"
                    });
            ViewBag.Data = data;
            return View();
        }
        #endregion

        public string queryjournals(int indType, int page = 0)
        {
            var journal = JournalBiz.GetAllJournal(c => c.IndType == indType && c.IsActive, page, 15);
            return journal.Select(c => new { Id = c.Id, Name = c.Name,img=c.CoverImg }).ToList().ToJson();
        }
    }
}
